package hhm.android.my

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.trello.rxlifecycle4.RxLifecycle
import com.trello.rxlifecycle4.android.ActivityEvent
import hhm.android.library.utils.BackListener
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.disposables.Disposable
import siau.android.base.HttpHelper
import siau.android.http.model.ChangePhoneRequest
import siau.android.http.model.MobileRequest
import java.util.concurrent.TimeUnit

class ChangePhoneViewModel : ViewModel() {

    private var subscribe: Disposable? = null
    var canGetCode = false
    var hasGetCode = MutableLiveData(false)
    var countDownNumber = MutableLiveData(60)
    var errorString = MutableLiveData<String>()
    var canBtn = MutableLiveData(false)

    fun startCountDown(o: Observable<ActivityEvent>, phone: String) {
        subscribe = Observable.interval(0,1, TimeUnit.SECONDS).observeOn(AndroidSchedulers.mainThread()).subscribe {
            val t = 59 - it.toInt()
            if (t == 0) {
                countDownNumber.value = 60
                hasGetCode.value = false
                subscribe?.dispose()
            } else {
                countDownNumber.value = t
            }
        }

        val request = MobileRequest(phone)
        HttpHelper().getCaptcha(request)?.compose(RxLifecycle.bindUntilEvent(o, ActivityEvent.STOP))?.subscribe({

        }, {
            errorString.value = it.message
        })
    }

    fun changePhone(phone: String, code: String, back: BackListener) {
        val r = ChangePhoneRequest(phone, code)
        HttpHelper().changePhone(r)?.subscribe({
            back.callBack()
        }, {
            errorString.value = it.message
        })
    }

    fun finish() {
        subscribe?.dispose()
    }
}